package com.jahentao.integrationTest.case08;

import java.util.concurrent.Semaphore;

/**
 * 享元模式设计资源池
 * 
 * @author jahentao
 *
 * @param <T> 资源类型
 */
public class Pool<T extends Resource> {

	private int maxAvailable; 
	private Semaphore available;
	
	public Pool(int maxAvailable) {
		this.maxAvailable = maxAvailable;
		available = new Semaphore(maxAvailable, true); // 信号量
		used = new boolean[maxAvailable];
	}

	public T getItem() throws InterruptedException {
		available.acquire();
		return getNextAvailableItem();
	}

	public void putItem(T x) {
		if (markAsUnused(x))
			available.release();
	}

	protected T[] items;
	
	public T[] getItems() {
		return items;
	}

	public void setItems(T[] items) {
		this.items = items;
	}

	protected boolean[] used;

	protected synchronized T getNextAvailableItem() {
		for (int i = 0; i < maxAvailable; ++i) {
			if (!used[i]) {
				used[i] = true;
				return items[i];
			}
		}
		return null;
	}

	protected synchronized boolean markAsUnused(T item) {
		for (int i = 0; i < maxAvailable; ++i) {
			if (item == items[i]) {
				if (used[i]) {
					used[i] = false;
					return true;
				} else
					return false;
			}
		}
		return false;
	}
}
